package com.sangmo.fts.process.storage.service;

import com.sangmo.boot.framework.common.errors.ServiceException;
import com.sangmo.boot.framework.common.errors.StandardErrors;
import com.sangmo.boot.framework.data.filter.PageResult;
import com.sangmo.boot.framework.data.filter.PageSearch;
import com.sangmo.boot.framework.plugin.dataview.crud.service.DelegateViewService;
import com.sangmo.boot.framework.plugin.dataview.crud.service.ViewService;
import com.sangmo.fts.common.utils.RandomUtils;
import com.sangmo.fts.process.storage.interfaces.CsfInboundCreation;
import com.sangmo.fts.process.storage.model.CsfOutbound;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class CsfOutboundService extends DelegateViewService<CsfOutbound> {

    @Autowired
    private CsfOutboundEntityService csfOutboundEntityService;

    @Autowired
    private CsfInboundEntityService csfInboundEntityService;

    @Autowired
    private CsfLadingBillService csfLadingBillService;

    @Override
    protected ViewService<CsfOutbound> getEntityService() {
        return csfOutboundEntityService;
    }

    public void dispatch(Long id) {
        CsfOutbound outbound = this.get(id);
        if (CsfOutbound.States.COMPLETED.equals(outbound.getState())) {
            throw new ServiceException(StandardErrors.CLIENT_ERROR.getStatus(), "error.csfOutbound.dispatch.state.wrong");
        }
        outbound.setDeliveryNo(RandomUtils.generateRandomNum(8));
        outbound.setState(CsfOutbound.States.COMPLETED);
        this.save(outbound);
        afterDispatch(outbound);
    }

    private void afterDispatch(CsfOutbound outbound) {
        CsfInboundCreation creation = new CsfInboundCreation();
        creation.setTrainingId(outbound.getTrainingId());
        creation.setOutboundId(outbound.getId());
        csfInboundEntityService.create(creation);
    }

    public PageResult listItemsByPage(Long id, PageSearch ps) {
        CsfOutbound outbound = this.get(id);
        return csfLadingBillService.listItemsByPage(outbound.getBillId(), ps);
    }
}
